package com.eascs.brand.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.loanapplyoplog.LoanapplyOpLog;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.BeanUtils;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.recordlog.constant.O2oLogType;
import com.eascs.app.dao.PageResult;
import com.eascs.brand.entity.O2oBrandEntity;
import com.eascs.brand.entity.O2oPartnerEntity;
import com.eascs.brand.form.BrandForm;
import com.eascs.brand.service.O2oBrandService;
import com.eascs.brand.service.O2oPartnerService;
import com.eascs.common.util.StringUtil;
import com.eascs.file.FileTypeConstants;
import com.eascs.partner.entity.DealerPartnerEntity;
import com.eascs.partner.service.JxsPartnerService;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.sys.SysPermissionService;
import com.eascs.workflow.common.vo.ModelResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/rbrand")
public class O2oBrandRestController extends O2oBiscController {

	@Autowired
	O2oBrandService brandService;

	@Autowired
	O2oPartnerService partnerService;
	
	@Reference
	SysOrgService sysOrgService;
	
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	
	@Autowired
	private BaseUtils baseUtils;
	
	@Reference
	SysPermissionService sysPermissionService;
	
	@Autowired
	private JxsPartnerService jxsPartnerService;
	/**
	 * 品牌联想接口
	 * @return
	 */
	@RequestMapping("/search")
	public BaseRestResult<List<Object[]>> searchBrand(String keywords) {
		List<Object[]> data = brandService.searchBrandPage(keywords);
		return BaseRestResult.buildRestResult(data);
	}
	
	/**
	 * 品牌信息添加页面
	 * @return
	 */
	@RequestMapping("/view_in")
	public BaseRestResult<String> viewInsert() {
		User user = UserHolder.getUser();
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		ViewContext.put("currentUser", user.getCname());
		ViewContext.put("currentUserCode", user.getNo());
		return HtmlRestResult.popHtmlFragment("/brand/brand_add");
	}
	
	/**
	 * @Description:
	 * 				<p>
	 *               插入品牌类型
	 *               </p>
	 * @author CXW
	 * @date 2016年11月15日 下午7:43:41
	 * @version V1.0
	 */
	@RequestMapping("/inbrand")
	public BaseRestResult<String> insert(BrandForm form) {
		ModelResult<Boolean> checkForm = checkForm(form);
		if (!checkForm.getModel()) {
			return BaseRestResult.warn(checkForm.getErrMsg());
		}
		if (!"BRA_SRCE_OTH".equals(form.getBrandSource())  ) {
			form.setBrandSourceDes(null);
		}
		if (!"OH".equals(form.getTheIndustry())) {
			form.setReOther(null);
		}
		O2oBrandEntity entity = new O2oBrandEntity();
		BeanUtils.copyProperties(form, entity);
		entity.setCreateTime(new Date());
		entity.setHostProvinceName(sysOrgService.getOrgByIds(entity.getHostProvince()).getOrgName());
		List<ActOrgEntity> actOrgEntity = sysOrgService.getOrgChildrenByOrgId(entity.getHostProvince());
		if (actOrgEntity == null || actOrgEntity.size() != 1) {
			return BaseRestResult.warn("找不到经办平台，请联系管理员");
		}
		entity.setOrgId(actOrgEntity.get(0).getUnitNo());
		entity.setOrgName(actOrgEntity.get(0).getOrgName());

		boolean result = brandService.getNameAndCode(entity.getBrandName(), entity.getBrandCode());
		if (!result) {
			return BaseRestResult.warn("该品牌已存在");
		}
		ModelResult<Boolean> insertResult = brandService.insert(entity);
		if (insertResult.isSuccess() && !insertResult.getModel()) {
			return BaseRestResult.warn(insertResult.getErrMsg());
		} 
		LoanapplyOpLog log = getEntity(UserHolder.getUser().getCname(), O2oLogType.BRAND_UPDATE_ARD, entity.getId(), "新增品牌信息");
		partnerService.saveEntityLog(log);
		return BaseRestResult.popHtmlFragmentUrl("/rbrand/view_up?parameter=" + entity.getId());
	}
	/**
	 * 品牌信息修改界面,审核通过情况下，由运维设置编辑权限
	 * @param parameter
	 * @return
	 */
	@RequestMapping("/view_up")
	public BaseRestResult<String> viewUpdate(String parameter) {
		O2oBrandEntity o2oBrandEntity = brandService.getEntityById(parameter);
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		ViewContext.put("brandEntity", o2oBrandEntity);
		return HtmlRestResult.popHtmlFragment("/brand/brand_edit");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               更新品牌类型
	 *               </p>
	 * @author CXW
	 * @date 2016年11月15日 下午7:43:41
	 * @version V1.0
	 */
	@RequestMapping("/upbrand")
	public BaseRestResult<String> update(BrandForm form) {
		if (!"BRA_SRCE_OTH".equals(form.getBrandSource())  ) {
			form.setBrandSourceDes(null);
		}
		if (!"OH".equals(form.getTheIndustry())) {
			form.setReOther(null);
		}
		O2oBrandEntity entity = new O2oBrandEntity();
		BeanUtils.copyProperties(form, entity);
		entity.setUpdateTime(new Date());
		entity.setHostProvinceName(sysOrgService.getOrgByIds(entity.getHostProvince()).getOrgName());
		List<ActOrgEntity> actOrgEntity = sysOrgService.getOrgChildrenByOrgId(entity.getHostProvince());
		if (actOrgEntity == null || actOrgEntity.size() != 1) {
			return BaseRestResult.warn("找不到经办平台，请联系管理员");
		}
		entity.setOrgId(actOrgEntity.get(0).getUnitNo());
		entity.setOrgName(actOrgEntity.get(0).getOrgName());
		
		if (!form.getOldBrandName().equals(entity.getBrandName())) {
			boolean result = brandService.getNameAndCode(entity.getBrandName(), entity.getBrandCode());
			if (!result) {
				return BaseRestResult.warn("该品牌已存在");
			}
		}
		ModelResult<Boolean> updateResult = brandService.update(entity);
		if (updateResult.isSuccess() && !updateResult.getModel()) {
			return BaseRestResult.warn(updateResult.getErrMsg());
		} 
		LoanapplyOpLog log = getEntity(UserHolder.getUser().getCname(), O2oLogType.BRAND_UPDATE_RD, entity.getId(), "修改品牌信息");
		partnerService.saveEntityLog(log);
		return BaseRestResult.info("修改品牌信息成功").andRefresh();
	}

	/**
	 * check品牌类型
	 * @param entity
	 * @return
	 */
	public ModelResult<Boolean> checkForm(BrandForm entity) {
		ModelResult<Boolean> modelResult=new ModelResult<>();
		if ("BRA_SRCE_OTH".equals(entity.getBrandSource()) && StringUtils.isEmpty(entity.getBrandSourceDes())) {
			modelResult.setErrMsg("请填写品牌来源");
			modelResult.setModel(false);
			return modelResult;
		}
		if ("OH".equals(entity.getTheIndustry()) && StringUtils.isEmpty(entity.getReOther()) ) {
			modelResult.setErrMsg("请填写品牌所属行业");
			modelResult.setModel(false);
			return modelResult;			
		}
		modelResult.setModel(true);	
		return modelResult;
	}
	
	/**
	 * 局部加载上传附件
	 * @param id
	 * @return
	 */
	@RequestMapping("/loadfile")
	public HtmlRestResult querySQBZJFile(String id) {
		queryDataList(id, FileTypeConstants.BRAND_TYPE_RPMENT,null);
		ViewContext.put("id", id);
		return HtmlRestResult.html("/brand/brandfile");
	}
	
	/**
	 * 附件列表
	 * @param loanapplyNo
	 * @param code
	 * @param detailFlag
	 */
	public void queryDataList(String loanapplyNo, String code, String detailFlag) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null,
				ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		if (!"detail".equals(detailFlag)) {
		AjaxConfirmButton[] dealButton=null;
		dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		paginationInfo.setMoreButtons(dealButton);
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResult", paginationInfo);// 个人附件
	}
	
	/**
	 * 启动审批流程
	 * @param parameter
	 * @return
	 */
	@RequestMapping("/startFlow")
	public BaseRestResult<String> startFlow(String parameter) {
		O2oBrandEntity o2oBrandEntity = brandService.getEntityById(parameter);
		ModelResult<Boolean> checkRole = isCurrentRole(o2oBrandEntity, "startFlow");
		if (!checkRole.getModel()) {
			return BaseRestResult.warn(checkRole.getErrMsg());
		}
		ModelResult<Boolean> startUp = brandService.startUp(parameter);
		if (startUp.isSuccess() && startUp.getModel() ) {
			return BaseRestResult.info("流程启动成功").andRefresh();
		} else {
			return BaseRestResult.warn(startUp.getErrMsg());
		}
	}
	
	/**
	 * check当前用户是否为经办人
	 * @param entity
	 * @return
	 */
	public ModelResult<Boolean> isCurrentRole(O2oBrandEntity entity, String operateType) {
		ModelResult<Boolean> modelResult=new ModelResult<>();
		User user = UserHolder.getUser();
		if (!user.getNo().equals(entity.getOperatorId()) && !user.isSuperAdministrator()) {
			if ("edit".equals(operateType)) {
				modelResult.setErrMsg("该信息只能由经办人编辑");
			} else if ("delete".equals(operateType)) {
				modelResult.setErrMsg("该信息只能由经办人删除");
			} else if ("startFlow".equals(operateType)) {
				modelResult.setErrMsg("该流程只能由经办人发起");
			}
			modelResult.setModel(false);	
			return modelResult;
		}
		modelResult.setModel(true);
		return modelResult;
		
	}
	
	/**
	 * 查询审批详情
	 * @param approvalStatus
	 * @param referId
	 * @param nodeAuditorId
	 * @return
	 */
	@RequestMapping("/view_flow")
	public BaseRestResult<String> viewFlow(String approvalStatus, String referId, String nodeAuditorId) {
		String approvalUrl = baseUtils.getApprovalUrl(nodeAuditorId, ProcessTemplate.PROECESS_TYPE_AUDIT_BP);// 审批代办列表详情URL
		O2oBrandEntity brandEntity = brandService.getEntityById(referId);
		queryDataList(referId, FileTypeConstants.PARTNER_TYPE_RPMENT,"detail");
		String agreeUrl = baseUtils.getApprovalAgreeUrl(referId, nodeAuditorId, ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("brandEntity", brandEntity);
		ViewContext.put("approvalUrl", approvalUrl);
		ViewContext.put("parameter", referId);
		ViewContext.put("approvalStatus", approvalStatus);//流程经办状态是待办/已办/已发起，待办状态才显示审批栏
		return HtmlRestResult.popHtmlFragment("/brand/brand_flow");
	}
	/**
	 * 删除品牌信息
	 * @param parameter
	 * @return
	 */
	@RequestMapping("/deleteBrand")
	public BaseRestResult<String> deleteBrand(String parameter) {
		O2oBrandEntity o2oBrandEntity = brandService.getEntityById(parameter);
		ModelResult<Boolean> checkRole = isCurrentRole(o2oBrandEntity, "delete");
		if (!checkRole.getModel()) {
			return BaseRestResult.warn(checkRole.getErrMsg());
		}
		if (StringUtil.isEmpty(parameter)) {
			return BaseRestResult.warn("参数为空，无法删除！");
		} else {
			ModelResult<Boolean> deleteResult = brandService.delete(parameter);
			if (deleteResult.isSuccess() && deleteResult.getModel()) {
				return BaseRestResult.info("删除成功").andRefresh();
			} else {
				return BaseRestResult.warn(deleteResult.getErrMsg());
			}
		}
	}
	
	/**
	 * @Description:
	 * 				<p>
	 *               合作方管理 详情按钮  
	 *               </p>
	 * @author LMX
	 * @date 2017年6月1日
	 * @version V1.0
	 */
	@RequestMapping("/buttons")
	public BaseRestResult<String> bottons(String id) {
		User user = UserHolder.getUser();
		O2oPartnerEntity partnerEntity = partnerService.getEntityById(id);

		List<Button> bottons = new ArrayList<>();
		if (partnerEntity != null) {
			if (!StringUtils.isEmpty(partnerEntity.getWfStatus() + "")) {
				
				if ("-1".equals(partnerEntity.getWfStatus() + "") || "3".equals(partnerEntity.getWfStatus() + "")) {
						bottons.add(ButtonHelper.createAjaxConfirmButton("删除", "/rpartner/delete?parameter="+ id, "delPartner"));
						bottons.add(ButtonHelper.createAjaxConfirmButton("发起流程", "/rpartner/startFlow?id=" + id, "startPartnerFlow"));
					if (user.getNo().equals(partnerEntity.getOperatorId() + "") || user.isSuperAdministrator()) {
						bottons.add(ButtonHelper.createAjaxButton("编辑", "/rpartner/view_edit?parameter=" + id, "editPartner"));
					}				
				}else if ("0".equals(partnerEntity.getWfStatus() + "")) {
					ModelResult<Boolean> result = sysPermissionService.checkAuth(user.getNo(), "ZBPPSH");
					if ( result.isSuccess() && result.getModel()) {
						bottons.add(ButtonHelper.createAjaxButton("编辑", "/rpartner/view_edit?parameter=" + id, "editPartner"));
					}
				}
				
			}
		}
		ViewContext.put("buttons", bottons);
		ViewContext.put("entity", partnerEntity);
		return new HtmlRestResult("generation/detail_button");
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               脱敏
	 *               </p>
	 * @author LMX
	 */
	@RequestMapping(value = "/jxs_workflow_model_view")
	public HtmlRestResult jxsWorkflowModelView(String parameter) {
		DealerPartnerEntity dealerPartnerEntity = jxsPartnerService.getEntityById(parameter);
		ViewContext.put("vo", dealerPartnerEntity);	
		return HtmlRestResult.popHtmlFragment("/partner/jxs_workflow_model_view");
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               脱敏
	 *               </p>
	 * @author LMX
	 */
	@RequestMapping(value = "/workflow_model_view")
	public HtmlRestResult workflowModelView(String parameter) {
		O2oPartnerEntity o2oPartnerEntity = partnerService.getEntityById(parameter);
		ViewContext.put("vo", o2oPartnerEntity);
		return HtmlRestResult.popHtmlFragment("/partner/workflow_model_view");
	}
	
}
